import 'package:PollOnLine/ui/home/task_detail/task_detail_view.dart';
import 'package:PollOnLine/utils/logger_utils.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../bean/UserTask.dart';
import '../../../network/network.dart';
import '../../../utils/EventBusUtils.dart';
import '../../../utils/utils.dart';
import '../../../values/MyColors.dart';
import '../task_detail/task_detail_view_ipad.dart';
import 'task_list_state.dart';

class TaskListLogic extends GetxController {
  final TaskListState state = TaskListState();

  TaskListLogic(String status) {
    state.status = status;
  }

  // 刷新控制器 initialRefresh 是否最初刷新
  late RefreshController refreshController = RefreshController(initialRefresh: false);

  late StreamSubscription<TaskList>? subscription;

  @override
  void onReady() {
    super.onReady();
    // 监听刷新
    subscription = bus.listen((event) => onRefresh());

    listUserTask();
  }

  void goToNextPoll(String? taskId) {
    if (isPad(Get.context!)) {
      Get.to(() => const TaskDetailPageIpad(title: "任务详情"), arguments: taskId);
    } else {
      Get.to(() => const TaskDetailPage(title: "任务详情"), arguments: taskId);
    }
  }

  /// 刷新
  Future<void> onRefresh() async {
    state.currentPage = 1;
    // 监视网络获取
    await Future.delayed(const Duration(milliseconds: 1000));
    // 如果失败,使用refreshFailed ()
    await listUserTask();
    refreshController.refreshCompleted();
    refreshController.resetNoData();
    bus.fire(HomeEvent());
  }

  /// 加载
  Future<void> onLoading() async {
    // 监视网络获取
    await Future.delayed(const Duration(milliseconds: 1000));
    // 如果完成使用loadFailed()，如果没有数据返回，使用LoadNodata()
    int totalPages = state.userTask?.totalPages ?? 1;

    if (state.currentPage < totalPages) {
      state.currentPage++;
      await listUserTask();
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  /// 获取任务列表
  Future<void> listUserTask() async {
    Map<String, dynamic> page = {
      "status": state.status,
    };
    Map<String, dynamic> param = {
      "currentPage": state.currentPage,
      'pageSize': 10,
      'param': page,
    };

    ResultData resultData = await Api.listUserTask(param);
    if (resultData.isSuccess) {
      if (state.currentPage == 1) {
        state.userTask = UserTask.fromJson(resultData.data['data']);
      } else {
        state.userTask?.content?.addAll(UserTask.fromJson(resultData.data['data']).content as Iterable<Content>);
      }
      update();
    }
  }

  dynamic getStatus(Content item) {
    late var str = {};
    String status = item.status ?? "";
    switch (status) {
      case "1":
        str = {"tagText": "进行中", "textColor": MyColors.FF1060DD, "bgColor": MyColors.FFDBE7FA, "proColor": MyColors.FF1060DD};
      case "2":
        str = {"tagText": "截止", "textColor": MyColors.FFED6C04, "bgColor": MyColors.FFFCF0DF, "proColor": MyColors.FFE9961F};
      default:
        str = {"tagText": "已完成", "textColor": MyColors.FF3AA858, "bgColor": MyColors.FFDDF3E5, "proColor": MyColors.FF57BB72};
    }
    return str;
  }

  // 获取百分比
  String getPercent(int? writeCount, int? collectCount) {
    int myWriteCount = writeCount ?? 0;
    int myCollectCount = collectCount ?? 1;
    String str = '${(myWriteCount / myCollectCount * 1000).round() / 10.toDouble()}';
    if (str.substring(str.length - 1, str.length) == "0") {
      str = '${double.parse(str).toInt().toString()}%';
    } else {
      str = "$str%";
    }
    return str;
  }

  @override
  void onClose() {
    super.onClose();
    subscription?.cancel();
  }
}
